package com.by.and_widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 *
 */
public class RecycleImageView extends ImageView {
    /**
     * 系统默认ImageView
     */
    public static final int DEFAULT = 0;
    /**
     * 圆形ImageView, 支持设置边框宽度和边框颜色
     */
    public static final int CIRCLE = 1;
    /**
     * 圆角ImageView,支持设置圆角角度、边框宽度和边框颜色
     */
    public static final int ROUND = 2;
    /**
     * 宽高成比例的ImageView,支持设置宽高的比例，默认1:1
     */
    public static final int RATIO = 3;

    public static final int DEFAULT_TYPE = DEFAULT;
    public static final int DEFAULT_BORDER_WIDTH = 0;
    public static final int DEFAULT_BORDER_COLOR = Color.WHITE;
    public static final int DEFAULT_ROUND_RADIUS = 0;
    public static final float DEFAULT_RATIO = 1.0F;

    private int type = DEFAULT_TYPE;
    private int borderWidth = DEFAULT_BORDER_WIDTH;
    private int borderColor = DEFAULT_BORDER_COLOR;
    private float roundRadius = DEFAULT_ROUND_RADIUS;
    private float roundBorderRadius = DEFAULT_ROUND_RADIUS;
    private float ratio = DEFAULT_RATIO;
    private float circleRadius;
    /**
     * 绘图的Paint
     */
    private Paint mBitmapPaint;
    private Paint mBorderPaint;
    private Matrix mMatrix;
    private BitmapShader mBitmapShader;
    private RectF mRoundRect;

    public RecycleImageView(Context context) {
        this(context, null);
    }

    public RecycleImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RecycleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        getAttrs(attrs, defStyleAttr);
        init();
    }

    private void getAttrs(AttributeSet attrs, int defStyleAttr) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RecycleImageViewStyle, defStyleAttr, 0);
        type = a.getInt(R.styleable.RecycleImageViewStyle_type, DEFAULT_TYPE);
        borderWidth = a.getResourceId(R.styleable.RecycleImageViewStyle_border_width, 0);
        if (borderWidth == 0) {
            borderWidth = a.getDimensionPixelSize(R.styleable.RecycleImageViewStyle_border_width, DEFAULT_BORDER_WIDTH);
        }
        borderColor = a.getResourceId(R.styleable.RecycleImageViewStyle_border_color, 0);
        if (borderColor == 0) {
            borderColor = a.getColor(R.styleable.RecycleImageViewStyle_border_color, DEFAULT_BORDER_COLOR);
        }
        roundRadius = a.getDimensionPixelSize(R.styleable.RecycleImageViewStyle_round_radius, DEFAULT_ROUND_RADIUS);
        roundBorderRadius = a.getDimensionPixelSize(R.styleable.RecycleImageViewStyle_round_border_radius, DEFAULT_ROUND_RADIUS);
        ratio = a.getFloat(R.styleable.RecycleImageViewStyle_ratio, DEFAULT_RATIO);
        a.recycle();
    }

    private void init() {
        mMatrix = new Matrix();
        mBitmapPaint = new Paint();
        mBitmapPaint.setAntiAlias(true);
        mBorderPaint = new Paint();
        mBorderPaint.setAntiAlias(true);
        mBorderPaint.setStyle(Paint.Style.STROKE);
        mBorderPaint.setStrokeWidth(borderWidth);
        mBorderPaint.setColor(borderColor);
    }


    @Override
    protected Parcelable onSaveInstanceState() {
        super.onSaveInstanceState();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putInt("borderWidth", borderWidth);
        bundle.putInt("borderColor", borderColor);
        bundle.putFloat("roundRadius", roundRadius);
        bundle.putFloat("ratio", ratio);
        bundle.putFloat("circleRadius", circleRadius);
        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        super.onRestoreInstanceState(state);
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            type = bundle.getInt("type");
            borderWidth = bundle.getInt("borderWidth");
            borderColor = bundle.getInt("borderColor");
            roundRadius = bundle.getFloat("roundRadius");
            ratio = bundle.getFloat("ratio");
            circleRadius = bundle.getFloat("circleRadius");
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int resultWidth = 0;
        int resultHeight = 0;
        if (type == CIRCLE) {
            resultWidth = resultHeight = Math.min(widthSize, heightSize);
            circleRadius = resultWidth / 2;
            setMeasuredDimension(resultWidth, resultHeight);
        } else if (type == RATIO) {
            if (widthMode == MeasureSpec.EXACTLY) {
                resultWidth = widthSize;
            } else if (widthMode == MeasureSpec.AT_MOST) {
                resultWidth = Math.min(getDrawableWidth(), widthSize);
            }
            resultHeight = (int) (widthSize * ratio);
            setMeasuredDimension(resultWidth, resultHeight);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    private int getDrawableWidth() {
        Drawable d = getDrawable();
        return Math.max(d.getIntrinsicWidth(), 0);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (type == DEFAULT || type == RATIO) {
            super.onDraw(canvas);
            return;
        }

        if (type == CIRCLE) {
            if (getDrawable() == null) {
                return;
            }
            setUpShader();
            canvas.drawCircle(circleRadius, circleRadius, circleRadius - borderWidth / 2, mBitmapPaint);
            if (borderWidth > 0) {
                canvas.drawCircle(circleRadius, circleRadius, circleRadius - borderWidth / 2, mBorderPaint);
            }
        } else if (type == ROUND) {
            setUpShader();
            canvas.drawRoundRect(mRoundRect, roundRadius, roundRadius,
                    mBitmapPaint);
            if (borderWidth > 0) {
                canvas.drawRoundRect(mRoundRect, roundRadius, roundRadius,
                        mBorderPaint);
            }
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mRoundRect = new RectF(0, 0, getWidth(), getHeight());
    }

    /**
     * 初始化BitmapShader
     */
    private void setUpShader() {
        Drawable drawable = getDrawable();
        if (drawable == null) {
            return;
        }

        Bitmap bmp = drawableToBitamp(drawable);
        // 将bmp作为着色器，就是在指定区域内绘制bmp
        mBitmapShader = new BitmapShader(bmp, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        float scale = 1.0f;
        if (type == CIRCLE) {
            // 拿到bitmap宽或高的小值
            int bSize = Math.min(bmp.getWidth(), bmp.getHeight());
            scale = getWidth() * 1.0f / bSize;
        } else if (type == ROUND) {
            // 如果图片的宽或者高与view的宽高不匹配，计算出需要缩放的比例；缩放后的图片的宽高，一定要大于我们view的宽高；所以我们这里取大值；
            scale = Math.max(getWidth() * 1.0f / bmp.getWidth(), getHeight()
                    * 1.0f / bmp.getHeight());
        }
        // shader的变换矩阵，我们这里主要用于放大或者缩小
        mMatrix.setScale(scale, scale);
        // 设置变换矩阵
        mBitmapShader.setLocalMatrix(mMatrix);
        // 设置shader
        mBitmapPaint.setShader(mBitmapShader);
    }

    private Bitmap drawableToBitamp(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bd = (BitmapDrawable) drawable;
            return bd.getBitmap();
        }
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }


    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        setImageDrawable(null);
    }
}
